package com.tensquare.friend.controller;

import com.tensquare.friend.client.UserClient;
import com.tensquare.friend.service.FriendService;
import com.tensquare.friend.service.NoFriendService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by WF on 2020/4/4 15:30
 */
@RestController
@RequestMapping("friend")
public class FriendController {
    @Autowired
    private FriendService friendService;
    @Autowired
    private NoFriendService noFriendService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserClient userClient;
    //1.添加好友
    @PutMapping("like/{friendid}/{type}")
    public Result addFriend(@PathVariable String friendid, @PathVariable String type){
        //1.1)从请求作用域中得到claims对象
        Claims claims = (Claims) request.getAttribute("claims");
        System.out.println("claims = " + claims);
        //1.2)判断是否有值，并且得到key为roles的值，看是否为user
        if(claims != null){
            String roles = claims.get("roles") + "";
            if(!("user".equals(roles) || "admin".equals(roles))){
                return new Result(false,StatusCode.ACCESSERROR,"无权访问！");
            }
            //1.3）添加好友
            if(type.equals("1")){       //喜欢
                int count = friendService.addFriend(claims.getId(),friendid);
                if(count == 0){
                    return new Result(false,StatusCode.REPERROR,"重复添加好友！");
                }
                //更新粉丝数及关注数
                userClient.incFansCount(claims.getId(),1);
                userClient.incFollowCount(friendid,1);
            }else{                      //不喜欢
                noFriendService.addNoFriend(claims.getId().toString(),friendid);
            }
        }
        return new Result(true,StatusCode.OK,"添加好友成功！");
    }
    //2.删除好友
    @DeleteMapping("{friendid}")
    public Result delete(@PathVariable String friendid){
        //2.1)得到claims对象
        Claims claims = (Claims) request.getAttribute("claims");
        System.out.println("claims = " + claims);
        //2.2)判断其角色是否为admin
        if(claims != null){
            String roles = (String) claims.get("roles");
            if(StringUtils.isNotBlank(roles) && "admin".equals("admin")){   //必须是管理员才能删除
                friendService.delete(claims.getId(),friendid);
                //更新粉丝数和关注数
                userClient.incFansCount(claims.getId(),-1);
                userClient.incFollowCount(friendid,-1);
                return new Result(true,StatusCode.OK,"删除用户成功！");
            }
        }
        return new Result(false,StatusCode.ERROR,"删除用户失败！");
    }
}
